package fischl;

import com.google.gson.reflect.TypeToken;
import fischl.log.Log;
import fischl.log.LogFactory;
import fischl.model.Room;
import okhttp3.internal.Util;
import okio.BufferedSource;
import okio.Okio;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public final class RoomLoader {
  private static final Log log = LogFactory.get("roomLoader");

  private static List<Room> cache;

  public static List<Room> load() {
    if (cache != null) return cache;
    // load builtin room
    cache = new ArrayList<>();
    if (!Config.disableBuiltinRoom) {
      if (Config.isDouyu) {
        log.i("loading douyu builtin rooms");
        InputStream in = Room.class.getClassLoader().getResourceAsStream("douyu.json");
        if (in != null) {
          load(in, cache);
        }
      } else {
        log.i("loading huya builtin rooms");
        InputStream in = Room.class.getClassLoader().getResourceAsStream("huya.json");
        if (in != null) {
          load(in, cache);
        }
      }
    }
    File file = new File(System.getProperty("user.home"), "room.json");
    if (file.exists()) {
      log.i("loading user home room files");
      try {
        load(new FileInputStream(file), cache);
      } catch (Exception e) {
        log.e(e);
      }
    }
    String extraPath = Config.extraRoomPath;
    if (extraPath != null && !extraPath.isEmpty()) {
      file = new File(extraPath);
      if (file.exists()) {
        log.i("loading extra rooms");
        try {
          load(new FileInputStream(file), cache);
        } catch (Exception e) {
          log.e(e);
        }
      }
    }
    log.i("loaded {} rooms", cache.size());
    return Collections.unmodifiableList(cache);
  }

  private static void load(InputStream in, List<Room> out) {
    Type type = TypeToken.getParameterized(List.class, Room.class).getType();
    try {
      BufferedSource source = Okio.buffer(Okio.source(in));
      List<Room> room = Global.gson().fromJson(source.readUtf8(), type);
      out.addAll(room);
    } catch (Exception e) {
      log.e(e);
    } finally {
      Util.closeQuietly(in);
    }
  }
}
